import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';

class MyNotification extends Notification {
  final String msg;

  MyNotification(this.msg);
}

class NotificationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _NotificationPage();
  }
}

class _NotificationPage extends State<NotificationPage> {
  String _msg = "";

  @override
  Widget build(BuildContext context) {
    return NotificationListener<MyNotification>(
      onNotification: (notification) {
        setState(() {
          _msg += notification.msg + "  ";
        });
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text("Notification"),
          centerTitle: true,
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Builder(builder: (context) {
                return ElevatedButton(
                  //按钮点击时分发通知
                  onPressed: () => MyNotification("Hi").dispatch(context),
                  child: Text("Send Notification"),
                );
              }),
              Text(_msg)
            ],
          ),
        ),
      ),
    );
  }
}
